import {DataGrid, GridColumn, GridColumnGroup, GridHeaderRow, LinkButton} from "rc-easyui";
import React, {useContext, useState} from "react";
import {AppLayoutContext, withCheckGrid} from "@kordar/easyui-tpl";
import {FormDataType} from "@kordar-lib/base";
import {tfield, tparam, tt} from "@kordar-lib/i18n";
import {BucketDetailContext} from "./context";
import TitlePanel from "./title";
import {$prompt, $toast, Access} from "@kordar/easyui";
import {invoke} from "lodash-es";
import {copy, cut, del, download, rename} from "../../../service/bucket_service";
import {downloadWithA} from "../../../util/helper";
import {setPaste, setPasteType} from "../../../store/bucket";


let CheckGrid = withCheckGrid(DataGrid)

const TablePanel = ({id}) => {

    const {pageConfig, ctx, ctxState, bucket, setCurrentPath, currentPath} = useContext(BucketDetailContext)

    const { dispatch, useAppSelector } = useContext(AppLayoutContext);
    const pasteData = useAppSelector?.((state) => state?.bucket.paste)
    const pasteType = useAppSelector?.((state) => state?.bucket.pasteType)


    const toolbar = () => {

        return (
            <React.Fragment>
                <div>
                    <TitlePanel />
                </div>
                <div style={{padding: 4, display: 'flex', flexDirection: 'row', alignItems: 'center', justifyContent: 'start'}}>
                    <LinkButton plain className="k-color-success" iconCls="iconfont icon-refresh color-green"
                                onClick={() => ctx?.refresh()}>
                        {tparam(pageConfig, 'refresh.text', 'Refresh')}
                    </LinkButton>

                    {pasteData && pasteData.length>0 ?
                        <LinkButton
                            plain
                            iconCls="iconfont icon-paste color-red"
                            onClick={() => {
                                if (pasteType === "cut") {
                                    cut(id, pasteData, currentPath===''?'/':currentPath).then(() => {
                                        dispatch(setPaste([]))
                                        ctx?.refresh()
                                    })
                                }


                                if (pasteType === "copy") {
                                    copy(id, pasteData, currentPath===''?'/':currentPath).then(() => {
                                        dispatch(setPaste([]))
                                        ctx?.refresh()
                                    })
                                }


                            }}
                        >
                            {pasteData.length}
                        </LinkButton>
                        : ""
                    }

                    <Access ctx={ctx} point="cut">
                        <LinkButton
                            plain
                            iconCls="iconfont icon-cut1 color-dark-green"
                            onClick={() => {
                                let values = ctx?.tableSlectionValue()
                                if (values && values.length === 0) {
                                    $toast.error(tt("none_checkbox_warn", "Message", "Please select the object to operate!"))
                                    return
                                }

                                dispatch(setPaste(values))
                                dispatch(setPasteType("cut"))

                            }}
                        />
                    </Access>

                    <Access ctx={ctx} point="copy">
                        <LinkButton
                            plain
                            iconCls="iconfont icon-copy color-dark-green"
                            onClick={() => {
                                let values = ctx?.tableSlectionValue()
                                if (values && values.length === 0) {
                                    $toast.error(tt("none_checkbox_warn", "Message", "Please select the object to operate!"))
                                    return
                                }

                                dispatch(setPaste(values))
                                dispatch(setPasteType("copy"))
                            }}
                        />
                    </Access>

                </div>
            </React.Fragment>
        )
    }


    const renderOperation = ({value, row, rowIndex}) => {
        let openParam = {
            record: row,
            ctx: ctx,
            type: FormDataType.UPDATE,
            title: `${tparam(pageConfig, 'update.text', 'Update: {#name}')}`.replace('{#name}', row.username)
        }


        return (
            <>

                <Access ctx={ctx} point="rename">
                    <LinkButton plain iconCls="iconfont icon-rename color-dark-green"
                                disabled={row.file_type !== "file"}
                                onClick={() => {
                                    $prompt(tparam(pageConfig, "rename.text", "rename"), row.params.filename, (value) => {
                                        rename({id: id, filename: row.path, new_filename: value}).then(() => {
                                            ctx?.refresh()
                                        })
                                    })
                                }}
                    />
                </Access>

                <Access ctx={ctx} point="download">
                    <LinkButton
                        plain
                        iconCls="iconfont icon-download color-blue"
                        disabled={row.file_type !== "file"}
                        onClick={() => downloadWithA(download, {id: id, filename: row.path, name: row.params['filename']}, row.params['filename'])} />
                </Access>

                <Access ctx={ctx} point="upload">
                    <LinkButton plain onClick={() => invoke(refs, 'formdlg.open', openParam)}
                                iconCls="iconfont icon-upload color-dark-green"/>
                </Access>



                <Access ctx={ctx} point="delete">
                    <LinkButton
                        plain
                        iconCls="iconfont icon-del color-red"
                        onClick={() => {
                            if (row.file_type === "dir") {
                                ctx?.publish('remove-dir', {
                                    fn: del,
                                    params: {id: id, dir: row.path},
                                    success: () => ctx?.refresh()
                                })
                            } else {
                                ctx?.publish('remove', {
                                    fn: del,
                                    params: {id: id, filename: row.path},
                                    success: () => ctx?.refresh()
                                })
                            }

                        }} />
                </Access>

            </>
        )
    }

    const onRowDblClick = (row) => {
        if (row['file_type'] === "dir") {
            ctx.search({id: bucket.id, dir: row.path})
            setCurrentPath('/'+row.path)
        }
    }

    return (
        <>
            <CheckGrid
                toolbar={toolbar}
                data={ctxState.data}
                loading={ctxState?.loading}
                onRowDblClick={onRowDblClick}
                style={ctxState?.style}
                idField="id"
                selection={ctxState?.selectionValues}
                onSelectionChange={(selections) => ctx?.tableSelectionChange(selections)}
                ckWidth={20}
            >
                <GridColumn field="filename" title={tfield(pageConfig, 'filename.label', 'Filename')} width="120px"
                    render={({row}) => row?.params?.filename}/>
                <GridColumn field="path" title={tfield(pageConfig, 'path.label', 'Path')} width="150px"/>
                <GridColumn field="file_type" title={tfield(pageConfig, 'file_type.label', 'Type')} width="30px"/>
                <GridColumn field="file_ext" title={tfield(pageConfig, 'file_ext.label', 'Ext')} width="30px"/>
                <GridColumn field="last_modified" title={tfield(pageConfig, 'last_modified.label', 'Last Modified')}
                            width="75px"/>
                <GridColumnGroup frozen align="right" width="150px">
                    <GridHeaderRow>
                        <GridColumn align="center" render={renderOperation} width="150px"/>
                    </GridHeaderRow>
                </GridColumnGroup>
            </CheckGrid>
        </>
    )
}

export default TablePanel
